﻿using BUGCOME.Infrastructure.WebExtensions;
using BUGCOME.Service.Common;
using BUGCOME.ServiceCore.Filters;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace BUGCOME.Common.Api.Controllers
{
    /// <summary>
    /// 字典数据API控制器，处理字典查询请求
    /// </summary>
    [Verify] // 验证特性（如身份/权限预处理）
    [Route("commonapi/[controller]/[action]")] // 路由：commonapi/控制器名/方法名
    [ApiExplorerSettings(GroupName = "common")] // API文档分组为"common"
    public class DictDataController : BaseController
    {
        // 字典数据服务（处理核心业务）
        private readonly IDictDataService dictDataService;
        // 字典类型服务（处理类型相关业务）
        private readonly IDictTypeService dictTypeService;

        /// <summary>
        /// 构造函数：通过依赖注入初始化字典相关服务
        /// </summary>
        /// <param name="dictDataService">字典数据服务实例，用于处理字典数据业务</param>
        /// <param name="dictTypeService">字典类型服务实例，用于处理字典类型业务</param>
        public DictDataController(IDictDataService dictDataService, IDictTypeService dictTypeService)
        {
            this.dictDataService = dictDataService;
            this.dictTypeService = dictTypeService;
        }

        /// <summary>
        /// 字典数据列表查询接口
        /// </summary>
        [ActionPermissionFilter(Permission = "admin:dict:list")] // 需"admin:dict:list"权限
        [HttpPost] // POST请求
        public async Task<IActionResult> List([FromBody] DictDataQueryDto dto)
        {
            // 基础查询：获取字典数据列表
            var list = await dictDataService.SelectDictDataListAsync(dto);

            // 若字典类型以"sql_"开头，追加自定义SQL查询结果
            if (dto.dType.StartsWith("sql_"))
            {
                var sqlResult = await dictTypeService.SelectDictDataByCustomSqlAsync(dto.dType);
                list.Result.AddRange(sqlResult);
                list.TotalNum += sqlResult.Count;
            }

            // 返回成功响应
            return Success(list);
        }

        /// <summary>
        /// 批量获取指定字典类型的数据
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetDicts([FromBody] List<string> list)
        {
            var dataVos = await GetDictsAsync([.. list]);
            return Success(dataVos);
        }


        /// <summary>获取数据的异步接口</summary>
        /// <param name="dto">请求体中的参数对象，含long类型ID</param>
        /// <returns>包含查询结果的成功响应</returns>
        [HttpPost]
        public async Task<IActionResult> GetData([FromBody] ParmDto<long> dto)
        {
            var response = await dictDataService.SelectDictDataByIdAsync(dto.Value);
            return Success(response);
        }


        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        [ActionPermissionFilter(Permission = "admin:dict:add")]
        [Log(Title = "字典数据", BusinessType = BusinessType.INSERT)]
        [HttpPost]
        public async Task<IActionResult> AddData([FromBody] DictDataDto dict)
        {
            DictData dictData = dict.Adapt<DictData>().ToCreate(HttpContext);
            var response = await dictDataService.InsertDictDataAsync(dictData);
            return Success(response);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        [ActionPermissionFilter(Permission = "admin:dict:edit")]
        [Log(Title = "字典数据", BusinessType = BusinessType.UPDATE)]
        [HttpPost]
        public async Task<IActionResult> UpdateData([FromBody] DictDataDto dict)
        {
            DictData dictData = dict.Adapt<DictData>().ToUpdate(HttpContext);
            var response = await dictDataService.UpdateDictDataAsync(dictData);
            return Success(response);
        }

        /// <summary>
        /// 删除字典类型
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [ActionPermissionFilter(Permission = "admin:dict:remove")]
        [Log(Title = "字典类型", BusinessType = BusinessType.DELETE)]
        [HttpPost]
        public async Task<IActionResult> Remove([FromBody]ParmDto<string> dto)
        {
            long[] dictCodes = Common.Tools.SpitLongArrary(dto.Value);
            var response =await dictDataService.DeleteDictDataByIdsAsync(dictCodes);
            return Success(response);
        }


        /// <summary>
        /// 单个字典类型查询（允许匿名）
        /// </summary>
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> DictType([FromBody] ParmDto<string> dto)
        {
            if (dto == null || string.IsNullOrEmpty(dto.Value))
                return BadRequest("字典类型不能为空");

            var result = await dictDataService.SelectDictDataByTypeAsync(dto.Value);
            return Success(result);
        }

        /// <summary>批量查询字典数据（含自定义类型）</summary>
        private async Task<List<DictDataParamDto>> GetDictsAsync([FromBody] List<string> dicts)
        {
            var dataVos = new List<DictDataParamDto>();
            var list = await dictDataService.SelectDictDataByTypesAsync(dicts);

            foreach (var dic in dicts)
            {
                var vo = new DictDataParamDto
                {
                    DictType = dic,
                    List = list.FindAll(f => f.DictType == dic)
                };

                if (dic.StartsWith("cus_") || dic.StartsWith("sql_"))
                    vo.List.AddRange(await dictTypeService.SelectDictDataByCustomSqlAsync(dic));

                dataVos.Add(vo);
            }

            return dataVos;
        }
    }
}